package thread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class TestVolatile2 implements Runnable {
    public static volatile boolean flag = true;
    public static volatile int value;

    @Override
    public void run() {
        synchronized (TestVolatile2.class) {
            while (flag) {
                value++;
                value--;
            }

            System.out.println("flag is " + flag);
        }
    }

    public static void main(String[] args) throws InterruptedException {
        ExecutorService es = Executors.newCachedThreadPool();
        long l = System.currentTimeMillis();
        es.execute(new TestVolatile2());
        es.execute(() -> {
            try {
                Thread.sleep(1000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            TestVolatile2.flag = false;
            System.out.println("set flag = " + TestVolatile2.flag);
        });

        es.shutdown();
        es.awaitTermination(10L, TimeUnit.SECONDS);
        System.out.println(System.currentTimeMillis() - l);
    }
}
